import {ChangeDetectorRef, Component} from '@angular/core';
import {Events} from "ionic-angular";
import {CodePush, DownloadProgress, ILocalPackage, InstallMode, IRemotePackage} from '@ionic-native/code-push';

/**
 * Generated class for the UpdateComponent component.
 *
 * See https://angular.io/api/core/Component for more info on Angular
 * Components.
 */
@Component({
  selector: 'update',
  templateUrl: 'update.html'
})
export class UpdateComponent {

  isShow: boolean = false;
  isDownload: boolean = false;

  iRemotePackage: IRemotePackage;
  length: any = '0%';

  constructor(private events: Events,
              private cd: ChangeDetectorRef,
              private codePush: CodePush) {
    this.events.subscribe("update:open", (iRemotePackage) => this.open(iRemotePackage))
  }

  open(iRemotePackage: IRemotePackage) {
    this.isShow = true;
    this.iRemotePackage = iRemotePackage;
  }

  close() {
    this.isShow = false;
    this.iRemotePackage = null;
  }

  start() {
    if (this.iRemotePackage) {
      this.isDownload = true;
      this.iRemotePackage.download((iLocalPackage: ILocalPackage) => {
        this.success(iLocalPackage)
      }, (error) => {
        let msg = error.message;
        if (error.message == 'null') msg = '当前手机系统不支持此更新模式，请重新下载最新程序';
        this.error(msg)
      }, (downloadProgress: DownloadProgress) => {
        this.download(downloadProgress);
      })
    }
  }

  download(downloadProgress) {
    let totalBytes = downloadProgress.totalBytes;
    let receivedBytes = downloadProgress.receivedBytes;
    let proportion = totalBytes == receivedBytes ? '100' : Math.round(receivedBytes / totalBytes * 100);
    if (proportion) {
      proportion += '%';
    } else {
      proportion = '0%';
    }
    setTimeout(() => {
      this.length = proportion;
      this.cd.detectChanges();
    }, 200);
  }

  success(iLocalPackage: ILocalPackage) {
    iLocalPackage.install(() => {
      this.codePush.restartApplication().then(v => {
        this.codePush.notifyApplicationReady();
      })
    }, (error) => {
      this.error(error)
      }, {mandatoryInstallMode: InstallMode.IMMEDIATE})
  }

  error(error) {
    // this.dialog.showAlert(error)
  }
}
